//1. 引入vuex
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

//2. 创建数据仓库
//3. 暴露仓库，并注入到vue项目中
export default new Vuex.Store({
  //仓库中存储的交互数据
  state: {
    goodslist: [],  //商品大数组 { name: '热销榜', foods: [{商品1},{商品2}] }
    name: '张三',
  },
  //改变state的唯一方式！！vuex的数据只能vuex改
  mutations: {
    //初始化商品数组
    initgoodslist(state, newlist) {
      //因为服务器返回的数据缺失商品数量，自己增加
      for (const obj of newlist) {
        for (const child of obj.foods) {
          child.num = 0
        }
      }

      state.goodslist = newlist
      console.log(state.goodslist)
    },

    //改变一个商品的数量+1
    addnum(state, argobj) {
      // argobj {id: child.id, num: 1}

      for (const obj of state.goodslist) {
        for (const child of obj.foods) {
          if(child.id == argobj.id)
            child.num += argobj.num
        }
      }
    },
  }
}) //创建一个数据仓库
